<?php


namespace app\admin\logic;


use app\common\config\cache\CacheKey;
use app\common\config\Client;
use app\common\utils\Auth;
use think\facade\Db;

/**
 * Class User
 * @package app\admin\logic
 * @property \app\common\model\Role modelRole
 * @property \app\common\model\User modelUser
 * @property \app\common\model\UserRole modelUserRole
 */
class User extends LogicBase
{
    /**
     *  登录管理端
     */
    public function login($data){
        empty($data['username']) && exception('用户名不能为空');
        empty($data['password']) && exception('密码不能为空');

        $user = \app\common\model\User::with(['role'=> function($query){
            $query->where([
                'client' => getConfigModuleValue()
            ]);
        }])->where('username',$data['username'])->find();
        empty($user) && exception('用户不存在');

        $commonLogicUser = new \app\common\logic\User();
        !$commonLogicUser->verifyPassword($user['id'],$data['password']) && exception('用户密码不正确');

        $token = Auth::buildToken($user['id']);
        $loginCacheInfo = [
            'id' => $user['id'],
            'token_uuid' => $token['uuid'],
            'roles' => $user['role']['roles']
        ];

        cache(CacheKey::loginToken(getConfigModuleName())->key([$user['id']]),$loginCacheInfo);
        return ['token'=>$token['token']];
    }

    /**
     * 获取当前登录用户信息
     */
    public function current($userInfo){
        $userInfo = \app\common\model\User::with(['role'=> function($query){
            $query->where([
                'client' => getConfigModuleValue()
            ]);
        }])->find($userInfo->id);

        $userInfo['authorities'] = $userInfo->getAuthoritiesAttr();

        return $userInfo;
    }

    /**
     * 登出
     */
    public function logout($userInfo){
        cache(CacheKey::loginToken(getConfigModuleName())->key([$userInfo->id]),null);
    }

    /**
     *  获取角色列表
     */
    public function getList($data){
        $where = [];
        !empty($data['searchContent']) && $where[] = ['username|phone','like','%'.$data['searchContent'].'%'];
        return $this->modelUser
            ->with(['role'=> function($query){
                $query->where([
                    'client' => getConfigModuleValue()
                ]);
            }])
            ->where($where)
            ->paginate(10);
    }

    /**
     * 新增角色信息
     */
    public function add($data){
        Db::startTrans();
        try{
            $user = $this->modelUser->add($data,\app\admin\middleware\Auth::$user->id);
            $this->modelUserRole->add([
                'client' => getConfigModuleValue(),
                'uid' => $user['id'],
                'roles'=> empty($data['roles']) ? [] : $data['roles']
            ],\app\admin\middleware\Auth::$user->id);
            // 提交事务
            Db::commit();
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 编辑信息
     */
    public function update($data){
        Db::startTrans();
        try{
            $this->modelUser->edit($data,\app\admin\middleware\Auth::$user->id);
            $this->modelUserRole->editByClient([
                'uid'=>$data['id'],
                'client'=>getConfigModuleValue(),
                'client_id'=>0,
                'roles'=>empty($data['roles']) ? [] : $data['roles']
            ],\app\admin\middleware\Auth::$user->id);
            // 提交事务
            Db::commit();
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 编辑信息
     */
    public function editPassword($data){
        Db::startTrans();
        try{
            $this->modelUser->editPassword($data);
            // 提交事务
            Db::commit();
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 删除信息
     */
    public function del($data){
        $this->modelUser->del($data,\app\admin\middleware\Auth::$user->id);
    }
}